package com.example.demo.juc;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName TestAtomicDemo
 * @Description
 * @Author 51
 * @Date 2020年3月20日 上午11:34:09
 */
public class TestAtomicDemo {


    /**
     * i++ 的原子性问题：i++的操作分为三个步骤“读 - 改 - 写”
     * int temp =i
     * i =i+1
     * i = temp
     *
     * @return
     */
    private static int extracted() {
        int i = 10;
        i = i++;
        return i;

    }

    public static void main(String[] args) {
        AtomicDemo atomicDemo = new AtomicDemo();
        for (int i = 0; i < 10; i++) {
            new Thread(atomicDemo).start();
        }
    }
}

class AtomicDemo implements Runnable {
    //    private int seriaNumber = 0;
    //原子变量
    private AtomicInteger seriaNumber = new AtomicInteger();

    @Override
    public void run() {
        try {
            Thread.sleep(2000);
            //数据会重复
            System.out.println(Thread.currentThread().getName() + " : " + getSeriaNumber());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public int getSeriaNumber() {
//        return seriaNumber++;
        return seriaNumber.getAndIncrement();
    }
}